package com.zyy.game.tianlong.constant;

import com.zyy.game.tianlong.network.exception.LogicException;

import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 每局的牌堆
 *
 * @author relufi
 * @date 2019/8/5 0005
 */
public class CardGroup {
    private final Card[] cards;
    private final int maxIndex;
    private AtomicInteger index = new AtomicInteger();

    public CardGroup(int user) {
        if (user <= 1 || user > 6) {
            throw new LogicException("牌组人数不正确");
        }
        this.maxIndex = user * 3;
        cards = new Card[maxIndex];
        int count = 0;
        ThreadLocalRandom rnd = ThreadLocalRandom.current();
        while (count < maxIndex) {
            Card card = Card.ALL[rnd.nextInt(52)];
            boolean isExits = false;
            for (int i = 0; i < count; i++) {
                if (cards[i] == card) {
                    isExits = true;
                    break;
                }
            }
            if (!isExits) {
                cards[count] = card;
                count++;
            }
        }
    }

    public CardGroup() {
        this(6);
    }

    /**
     * 发牌
     *
     * @return 随机3张牌，从大到小排序 null:在牌堆空时返回null
     */
    public Card[] deal() {
        int index = this.index.getAndAdd(3);
        if (index >= maxIndex) {
            return null;
        }
        Card[] newCards = new Card[]{cards[index], cards[index + 1], cards[index + 2]};
        CardUtils.sort(newCards);
        return newCards;
    }

    public boolean isEnd() {
        return index.get() >= maxIndex;
    }

    @Override
    public String toString() {
        return "index =" + index.get() + " cards=" + Arrays.toString(cards);
    }
}
